#!/bin/bash
INSTALLDIR=$(cd "$(dirname "$0")"; pwd);

CHECK_PORT_SCRIPT=$INSTALLDIR/checkport.sh
CHECK_ERROR=0

CHECK_IP_SCRIPT=$INSTALLDIR/checkip.sh
CHECK_NUMBER_SCRIPT=$INSTALLDIR/checknumber.sh

DEFAULT_REMOVE_IP=127.0.0.1
DEFAULT_REMOVE_PORT=9000
DEFAULT_LOCAL_PORT=9000

REMOVE_IP=127.0.0.1
REMOVE_PORT=9000
LOCAL_PORT=9000

ERROR=1
CHECK_SUCCESS=1

input_remove_id () {
    IP_SUCCESS=1;
    while true
    do
        printf "Enter tunnel remote ip${DEFAULT_REMOVE_ID}:" $REMOVE_IP;
        read REMOVE_IP

		if [ -z "$REMOVE_IP" ] ; then
            REMOVE_IP=$DEFAULT_REMOVE_IP;
        fi

        if test -x $CHECK_IP_SCRIPT ; then
            $CHECK_IP_SCRIPT $REMOVE_IP
            if [ $? -eq 0 ]; then
		CHECK_SUCCESS=0;
                IP_SUCCESS=0;
                break;  
            fi
        fi
    done
    return $IP_SUCCESS;
}

input_remove_port () {

    PORT_SUCCESS=1;
    while true
    do 
        printf "Enter tunnel remote port(${DEFAULT_REMOVE_PORT}):" $REMOVE_PORT;
        read REMOVE_PORT
        if [ ! $REMOVE_PORT ]; then
            REMOVE_PORT=$DEFAULT_REMOVE_PORT;
        fi
	if test -x $CHECK_NUMVER_SCRIPT; then
            $CHECK_NUMBER_SCRIPT $REMOVE_PORT
            if [ $? -eq 0 ]; then
		CHECK_SUCCESS=0; 
	        PORT_SUCCESS=0;
	        break;      
            fi
	fi
    done 
    return $PORT_SUCCESS
}

input_local_port () {
    LOCAL_PORT_SUCCESS=1;
    while true
    do
        printf "Enter tunel local port(${DEFAULT_LOCAL_PORT}):" $LOCAL_PORT;
        read LOCAL_PORT
        if [ ! $LOCAL_PORT ]; then
            LOCAL_PORT=$DEFAULT_LOCAL_PORT
        fi
        if test -x $CHECK_NUMBER_SCRIPT; then
    	    $CHECK_NUMBER_SCRIPT $LOCAL_PORT
			if [ $? -eq 0 ]; then
                if test -x $CHECK_PORT_SCRIPT; then
                    $CHECK_PORT_SCRIPT $LOCAL_PORT
                    #检查端口占用情况，没有被占用
                    if [ $? -ne 0 ]; then
			CHECK_SUCCESS=0;
                        LOCAL_PORT_SUCCESS=0;
                        break;
                    else
                        LOCAL_PORT_SUCCESS=1; 
                    fi
    	        fi
            else
				echo 'The input port is not a number.' 
            fi
        fi
    done
    return $LOCAL_PORT_SUCCESS 
}


exec_ssh_tunnel () {
    if [ $CHECK_SUCCESS -eq 0 ]; then
        ssh -C -f -N -g -L $LOCAL_PORT:$REMOVE_IP:$REMOVE_PORT root@"$REMOVE_IP"
        ERROR=0;
	echo "REMOVE_IP="$REMOVE_IP > tunnel_config.conf
	echo "REMOVE_PORT="$REMOVE_PORT >> tunnel_config.conf
	echo "LOCAL_PORT="$LOCAL_PORT >> tunnel_config.conf 
    fi
}
input_remove_id && input_remove_port && input_local_port && exec_ssh_tunnel 
exit $ERROR

